package top.lshaci.learning.oauth2.server.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import top.lshaci.learning.oauth2.server.entity.Users;
import top.lshaci.learning.oauth2.server.mapper.UsersMapper;
import top.lshaci.learning.oauth2.server.model.User;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * UserDetailsServiceImpl
 *
 * @author lshaci
 * @since 1.0.0
 */
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UsersMapper usersMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中获取用户信息
        LambdaQueryWrapper<Users> query = Wrappers.lambdaQuery(Users.class).eq(Users::getUsername, username);
        Users users = usersMapper.selectOne(query);
        if (Objects.isNull(users)) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 用户的角色和权限信息也应该从数据库中查询
        String role = "ROLE_ADMIN";
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(role));
        return User.builder()
                .id("用户ID")
                .username(users.getUsername())
                .password(users.getPassword())
                .clientId("客户端ID")
                .authorities(authorities)
                .enabled(true)
                .build();
    }
}
